package com.minelx.datamicroscope.core.query;

import com.minelx.datamicroscope.core.condition.InOperand;
import com.minelx.datamicroscope.core.condition.KeyOperandCondition;
import com.minelx.datamicroscope.core.condition.RawCondition;
import com.minelx.datamicroscope.core.condition.ResourceNanny;
import com.minelx.datamicroscope.core.values.CommonField;
import com.minelx.hellopandas.core.DataFrameDescription;
import io.gitee.minelx.filesystem.File;
import io.gitee.minelx.filesystem.provider.FSRegistry;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import static com.minelx.datamicroscope.core.query.Query.onlyLocalFSRegistry;
import static io.gitee.minelx.filesystem.init.OpenPolicy.EXISTS;

public class RawConditionFactory {

    private final FSRegistry fsRegistry;

    public RawConditionFactory(FSRegistry fsRegistry) {
        this.fsRegistry = fsRegistry;
    }

    public RawCondition rawConditionFromDataFrameSource(List<AliasedKey> keys, DataFrameDescription valuesDescription) {
        File valuesFile = fsRegistry.file(valuesDescription.uri(), EXISTS);
        return RawCondition.in_or_and__with_inputStream_support(keys, valuesFile::inputStream, valuesDescription);
    }

    public RawCondition extraToRawCondition(KeyOperandCondition keyOperandCondition) {
        if (!(keyOperandCondition.operand() instanceof InOperand)) {
            return RawCondition.sticky(keyOperandCondition);
        }
        // convert in operand to RawInCondition
        InOperand operand = (InOperand) keyOperandCondition.operand();
        CommonField key = keyOperandCondition.containedFields().get(0);
        return RawCondition.in__with_common_list_values(key, operand.getValues());
    }

    public static RawConditionFactory general() {
        return new RawConditionFactory(onlyLocalFSRegistry());
    }
}
